﻿package com.cw.war.ui 
{
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.events.EventDispatcher;

	/**
	 * 可收缩下拉列表
	 * @author niuzha
	 */
	public class Accordion extends EventDispatcher 
	{
		private var titleAry : Array;
		private var content : DisplayObjectContainer;
		private var selectedView : DisplayObjectContainer;
		private var selectedIndex : int;
		private var maxHeight : int;

		public function getMaxHeight () : int 
		{
			return this.maxHeight;
		}

		public function setMaxHeight (titleNum : int) : void 
		{
			this.maxHeight = 278 - (25 * titleNum) - 2;
		}

		public function Accordion (content : DisplayObjectContainer) 
		{

			this.content = content; 
			this.titleAry = new Array( );
			selectedView = new Sprite( );
			selectedView.name = "sView";
		}

		public function getContent () : DisplayObjectContainer
		{
			return this.content;
		}

		private function showTitle () : void 
		{
			for(var index : int = 0; index < titleAry.length; index ++) 
			{
				this.content.addChild( (titleAry[index] as IAccordionCell).getContent( ) );
			}
		}

		private function clearTitle () : void 
		{
			for each(var title:IAccordionCell in titleAry) 
			{
				this.content.removeChild( title.getContent( ) );
			}
		}

		public function setSelectedIndex (index : int) : void 
		{
			this.selectedIndex = index;
		}

		public function addTitle (titleAry : Array) : void 
		{
			if(this.titleAry.length != 0) 
			{
				clearTitle( );
			}
			this.titleAry = titleAry;
			this.showTitle( );
		}

		private function refreshView () : void 
		{			
			selectedView.y = (selectedIndex + 1) * (titleAry[0] as IAccordionCell).getHeight( );
			for(var index : int = 0; index < titleAry.length; index ++) 
			{
				var cell : IAccordionCell = titleAry[index] as IAccordionCell;
				if(index > selectedIndex) 
				{
					cell.getContent( ).y = cell.getHeight( ) * index + selectedView.height;
				} 
				else 
				{
					cell.getContent( ).y = cell.getHeight( ) * index;
				}
				if(index != selectedIndex) 
				{
					cell.setSelected( false );
				} 
				else 
				{
					cell.setSelected( true );
				}
			}
			this.content.addChild( selectedView );
		}

		public function reset () : void 
		{
			this.selectedView.visible = false;
			for(var index : int = 0; index < titleAry.length; index ++) 
			{
				var cell : IAccordionCell = titleAry[index] as IAccordionCell;
				cell.getContent( ).y = cell.getHeight( ) * index;
				cell.setSelected( false );
			}
		}

		public function setSelectedView (view : DisplayObjectContainer) : void 
		{
			this.selectedView = view;
			refreshView( );
		}
	}
}


